<template>
  <!-- 动态背景 -->
  <canvas ref="bgCanvas" class="bg-canvas"></canvas>

  <div class="container">
    <h1 class="page-title font-orbitron">CLASSHUB</h1>

    <header>
      <div class="flex flex-col md:flex-row justify-between items-center gap-4">
        <!-- 品牌Logo -->
        <div class="brand">
          <div class="logo font-orbitron">CLASS<span>HUB</span></div>
        </div>

        <!-- 系统信息 -->
        <div class="system-info">
          <div class="system-info-item">
            <i class="fas fa-microchip text-primary"></i>
            <span>系统负载：{{ systemLoad }}%</span>
          </div>
          <div class="system-info-item">
            <i class="fas fa-wifi text-primary"></i>
            <span>网络状态：在线</span>
          </div>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main>
      <!-- 控制面板 -->
      <div class="control-panel">
        <el-button
          type="primary"
          class="el-button--create"
          @click="openDialog('create')"
        >
          <i class="fas fa-plus-circle"></i>
          <span>新建分类</span>
        </el-button>

        <el-input
          placeholder="搜索分类..."
          v-model="searchQuery"
          class="search-input"
          size="large"
        >
          <template #prefix>
            <i class="fas fa-search"></i>
          </template>
        </el-input>
      </div>

      <!-- 3D分类展示区 -->
      <div>
        <div v-if="categories.length === 0" class="loading-container">
          <div class="loading-text font-orbitron">分类数据加载中...</div>
          <div class="loading-indicators">
            <div class="loading-bar"></div>
            <div class="loading-bar"></div>
            <div class="loading-bar"></div>
          </div>
        </div>

        <div v-else class="categories-grid">
          <!-- 分类卡片 -->
          <div
            v-for="category in filteredCategories"
            :key="category.id"
            class="category-card"
            :class="{ flipped: category.flipped }"
            @click="flipCard(category)"
          >
            <div class="card-inner">
              <!-- 卡片正面 -->
              <div class="card-front">
                <div class="card-header">
                  <h3 class="card-title font-orbitron">
                    {{ category.name }}
                  </h3>
                  <div
                    class="status-indicator"
                    :style="{ backgroundColor: category.color }"
                  ></div>
                </div>
                <div class="card-content">
                  <div class="card-data">
                    <span class="card-label">文章数：</span>
                    <span class="card-value" :style="{ color: category.color }">
                      {{ category.articleCount }}
                    </span>
                  </div>
                  <div class="card-data">
                    <span class="card-label">最后更新：</span>
                    <span>{{ category.lastUpdate }}</span>
                  </div>
                </div>
              </div>

              <!-- 卡片背面 -->
              <div class="card-back">
                <el-button
                  type="primary"
                  class="w-full mb-4 action-button"
                  @click.stop="openDialog('edit', category)"
                >
                  <i class="fas fa-pencil"></i>
                  <span>编辑分类</span>
                </el-button>
                <el-button
                  type="danger"
                  class="w-full action-button"
                  @click.stop="deleteCategory(category.id)"
                >
                  <i class="fas fa-trash"></i>
                  <span>删除分类</span>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 数据可视化面板 -->
      <div class="charts-section">
        <!-- 分类统计图表 -->
        <div class="chart-container">
          <div class="chart-header">
            <h3 class="chart-title font-orbitron">分类统计</h3>
            <i class="fas fa-chart-bar chart-icon"></i>
          </div>
          <div>
            <canvas ref="categoryChart"></canvas>
          </div>
        </div>

        <!-- 文章分布图表 -->
        <div class="chart-container">
          <div class="chart-header">
            <h3 class="chart-title font-orbitron">文章分布</h3>
            <i class="fas fa-chart-pie chart-icon"></i>
          </div>
          <div>
            <canvas ref="articleChart"></canvas>
          </div>
        </div>
      </div>
    </main>
  </div>

  <!-- 创建/编辑弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    custom-class="dialog-card"
    width="90%"
    :before-close="closeDialog"
  >
    <el-form :model="form" class="dialog-form">
      <el-form-item label="分类名称">
        <el-input
          v-model="form.name"
          placeholder="输入分类名称（2-12个字符）"
          size="large"
        />
      </el-form-item>

      <el-form-item label="分类颜色">
        <div class="flex items-center gap-4">
          <el-color-picker v-model="form.color" />
          <div class="color-preview" :style="{ backgroundColor: form.color }">
            {{ form.color || "颜色预览" }}
          </div>
        </div>
      </el-form-item>

      <el-form-item label="排序值">
        <div class="flex items-center gap-4">
          <el-slider
            v-model="form.sortValue"
            :min="0"
            :max="100"
            show-input
            size="large"
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog" class="action-button">取消</el-button>
        <el-button type="primary" @click="handleSubmit" class="action-button">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import {
  ElButton,
  ElInput,
  ElDialog,
  ElForm,
  ElFormItem,
  ElColorPicker,
  ElSlider,
  ElMessage,
} from "element-plus";
import Chart from "chart.js/auto";

// 系统状态
const systemLoad = ref(32);

// 分类数据
const categories = ref([
  {
    id: 1,
    name: "人工智能",
    color: "#00ffff",
    articleCount: 45,
    lastUpdate: "2024-03-15",
    flipped: false,
  },
  {
    id: 2,
    name: "区块链",
    color: "#ff00ff",
    articleCount: 32,
    lastUpdate: "2024-03-14",
    flipped: false,
  },
  {
    id: 3,
    name: "量子计算",
    color: "#9D00FF",
    articleCount: 18,
    lastUpdate: "2024-03-13",
    flipped: false,
  },
]);

// DOM 引用
const bgCanvas = ref<HTMLCanvasElement | null>(null);
const categoryChart = ref<HTMLCanvasElement | null>(null);
const articleChart = ref<HTMLCanvasElement | null>(null);

// 搜索功能
const searchQuery = ref("");
const filteredCategories = computed(() => {
  if (!searchQuery.value) return categories.value;
  return categories.value.filter((category) =>
    category.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

// 弹窗状态
const dialogVisible = ref(false);
const formMode = ref<"create" | "edit">("create");
const currentCategoryId = ref<number | null>(null);

// 表单数据
const form = reactive({
  name: "",
  color: "#00ffff",
  sortValue: 50,
});

// 弹窗标题
const dialogTitle = computed(() => {
  return formMode.value === "create" ? "新建分类" : "编辑分类";
});

// 打开弹窗
function openDialog(
  mode: "create" | "edit",
  category?: (typeof categories.value)[number]
) {
  formMode.value = mode;

  if (mode === "edit" && category) {
    currentCategoryId.value = category.id;
    form.name = category.name;
    form.color = category.color;
    form.sortValue = 50;
  } else {
    form.name = "";
    form.color = "#00ffff";
    form.sortValue = 50;
  }

  dialogVisible.value = true;
}

// 关闭弹窗
function closeDialog() {
  dialogVisible.value = false;
}

// 表单提交
function handleSubmit() {
  if (!form.name.trim()) {
    ElMessage.warning("请输入分类名称");
    return;
  }

  if (formMode.value === "create") {
    // 添加新分类
    const newCategory = {
      id: Date.now(),
      name: form.name,
      color: form.color,
      articleCount: Math.floor(Math.random() * 50) + 5,
      lastUpdate: new Date().toISOString().split("T")[0],
      flipped: false,
    };

    categories.value.push(newCategory);
    ElMessage.success("分类添加成功");
    initCharts();
  } else if (currentCategoryId.value) {
    // 更新现有分类
    const index = categories.value.findIndex(
      (c) => c.id === currentCategoryId.value
    );
    if (index !== -1) {
      categories.value[index].name = form.name;
      categories.value[index].color = form.color;
      ElMessage.success("分类更新成功");
      initCharts();
    }
  }

  closeDialog();
}

// 删除分类
function deleteCategory(id: number) {
  const index = categories.value.findIndex((c) => c.id === id);
  if (index !== -1) {
    categories.value.splice(index, 1);
    ElMessage.success("分类已删除");
    initCharts();
  }
}

// 翻转卡片
function flipCard(category: (typeof categories.value)[number]) {
  category.flipped = !category.flipped;

  // 关闭其他翻转的卡片
  categories.value.forEach((c) => {
    if (c.id !== category.id) {
      c.flipped = false;
    }
  });
}

// 动态背景初始化
function initBackground() {
  if (!bgCanvas.value) return;

  const canvas = bgCanvas.value;
  const ctx = canvas.getContext("2d");
  if (!ctx) return;

  const width = window.innerWidth;
  const height = window.innerHeight;

  canvas.width = width;
  canvas.height = height;

  const gradient = ctx.createLinearGradient(0, 0, width, height);
  gradient.addColorStop(0, "#0a0a1a");
  gradient.addColorStop(1, "#1a1a3a");

  const particles = [];

  // 创建粒子
  for (let i = 0; i < 100; i++) {
    particles.push({
      x: Math.random() * width,
      y: Math.random() * height,
      radius: Math.random() * 2 + 1,
      speedX: (Math.random() - 0.5) * 2,
      speedY: (Math.random() - 0.5) * 2,
      color: `rgba(${Math.floor(Math.random() * 100)}, ${Math.floor(
        Math.random() * 255
      )}, ${Math.floor(Math.random() * 255)}, 0.${Math.floor(
        Math.random() * 5 + 1
      )})`,
    });
  }

  // 动画循环
  const animate = () => {
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, width, height);

    particles.forEach((particle) => {
      particle.x += particle.speedX;
      particle.y += particle.speedY;

      if (particle.x < 0 || particle.x > width) {
        particle.speedX *= -1;
      }

      if (particle.y < 0 || particle.y > height) {
        particle.speedY *= -1;
      }

      ctx.beginPath();
      ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
      ctx.fillStyle = particle.color;
      ctx.fill();
    });

    requestAnimationFrame(animate);
  };

  animate();
}

// 图表实例
let categoryChartInstance: Chart | null = null;
let articleChartInstance: Chart | null = null;

// 初始化图表
function initCharts() {
  if (!categoryChart.value || !articleChart.value) return;

  // 销毁现有的图表实例
  if (categoryChartInstance) {
    categoryChartInstance.destroy();
  }
  if (articleChartInstance) {
    articleChartInstance.destroy();
  }

  // 准备数据
  const names = categories.value.map((c) => c.name);
  const articleCounts = categories.value.map((c) => c.articleCount);
  const colors = categories.value.map((c) => c.color);

  // 分类统计图表（柱状图）
  categoryChartInstance = new Chart(categoryChart.value, {
    type: "bar",
    data: {
      labels: names,
      datasets: [
        {
          label: "文章数量",
          data: articleCounts,
          backgroundColor: colors.map((c) => `${c}bb`),
          borderColor: colors,
          borderWidth: 1,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false,
        },
      },
      scales: {
        y: {
          beginAtZero: true,
          grid: {
            color: "rgba(255, 255, 255, 0.1)",
          },
          ticks: {
            color: "rgba(255, 255, 255, 0.7)",
          },
        },
        x: {
          grid: {
            display: false,
          },
          ticks: {
            color: "rgba(255, 255, 255, 0.7)",
          },
        },
      },
    },
  });

  // 文章分布图表（饼图）
  articleChartInstance = new Chart(articleChart.value, {
    type: "doughnut",
    data: {
      labels: names,
      datasets: [
        {
          data: articleCounts,
          backgroundColor: colors.map((c) => `${c}aa`),
          borderColor: colors.map((c) => `${c}99`),
          borderWidth: 1,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: "right",
          labels: {
            color: "rgba(255, 255, 255, 0.7)",
            padding: 20,
            font: {
              size: 12,
            },
          },
        },
      },
    },
  });
}

// 组件挂载后初始化
onMounted(() => {
  // 初始化动态背景
  initBackground();

  // 初始化图表
  initCharts();

  // 窗口大小变化处理
  window.addEventListener("resize", () => {
    if (categoryChartInstance) {
      categoryChartInstance.resize();
    }
    if (articleChartInstance) {
      articleChartInstance.resize();
    }
  });

  // 模拟系统负载变化
  setInterval(() => {
    systemLoad.value = 20 + Math.floor(Math.random() * 30);
  }, 3000);
});
</script>

<style lang="less" scoped>
@primary: #00ffff;
@secondary: #ff00ff;
@accent: #9d00ff;
@dark: #0a0a1a;
@dark-card: rgba(10, 10, 26, 0.7);
@glow-blue: rgba(0, 255, 255, 0.3);
@glow-purple: rgba(255, 0, 255, 0.3);

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: "Inter", sans-serif;
  background-color: @dark;
  color: white;
  min-height: 100vh;
  overflow-x: hidden;
}

.font-orbitron {
  font-family: "Orbitron", sans-serif;
}

.bg-glass {
  backdrop-filter: blur(16px);
  background: @dark-card;
}

.container {
  position: relative;
  z-index: 10;
  padding: 1.5rem;
  overflow-y: auto;
   /* 滚动条美化 */
  scrollbar-width: thin;
  scrollbar-color: @primary @dark;
  
  &::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(10, 10, 26, 0.3);
    border-radius: 5px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: linear-gradient(45deg, @primary, @secondary);
    border-radius: 5px;
    box-shadow: 0 0 5px rgba(0, 255, 255, 0.5);
    transition: all 0.3s ease;
    
    &:hover {
      background: linear-gradient(45deg, lighten(@primary, 10%), lighten(@secondary, 10%));
      box-shadow: 0 0 8px rgba(0, 255, 255, 0.8);
    }
  }
}

header {
  margin-bottom: 3rem;
}

.brand {
  display: flex;
  align-items: center;
}

.logo {
  font-size: clamp(1.8rem, 4vw, 2.8rem);
  font-weight: 800;
  letter-spacing: 0.08em;
  background: linear-gradient(to right, @primary, @secondary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  position: relative;
}

.logo span {
  color: @secondary;
  font-style: italic;
}
span {
  color: #fff;
}
.system-info {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  font-size: 0.9rem;
  opacity: 0.8;
}

.system-info-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.control-panel {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  margin-bottom: 3rem;

  @media (min-width: 768px) {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
}

.el-button--create {
  background: linear-gradient(to right, @primary, @secondary);
  color: @dark;
  font-weight: bold;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 20px rgba(0, 255, 255, 0.2);
  }

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      to right,
      transparent,
      rgba(255, 255, 255, 0.2),
      transparent
    );
    transition: 0.5s;
  }

  &:hover::before {
    left: 100%;
  }
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
  padding: 0.5rem;
}

.category-card {
  height: 260px;
  perspective: 1000px;
  cursor: pointer;
}

.card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  transition: transform 0.7s;
  transform-style: preserve-3d;
}

.category-card.flipped .card-inner {
  transform: rotateY(180deg);
}

.card-front,
.card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  border-radius: 12px;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  background: @dark-card;
}

.card-front {
  border: 1px solid rgba(0, 255, 255, 0.3);
  box-shadow: 0 0 5px rgba(0, 255, 255, 0.5), 0 0 10px rgba(0, 255, 255, 0.3);
}

.card-back {
  border: 1px solid rgba(255, 0, 255, 0.3);
  box-shadow: 0 0 5px rgba(255, 0, 255, 0.5), 0 0 10px rgba(255, 0, 255, 0.3);
  transform: rotateY(180deg);
  justify-content: center;
  align-items: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.card-title {
  font-size: 1.25rem;
  font-weight: bold;
  background: linear-gradient(to right, @primary, @secondary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  box-shadow: 0 0 8px currentColor;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 1rem;
}

.card-data {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-label {
  font-size: 0.9rem;
  opacity: 0.8;
}

.card-value {
  font-weight: 500;
}

.charts-section {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1.5rem;
  margin-top: 3rem;

  @media (min-width: 992px) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.chart-container {
  background: @dark-card;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  transition: box-shadow 0.3s;

  &:hover {
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
  }
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.chart-title {
  font-size: 1.125rem;
  font-weight: 600;
  background: linear-gradient(to right, @primary, @secondary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.chart-icon {
  font-size: 1.25rem;
  color: @primary;
  opacity: 0.7;
}

@keyframes glow {
  0% {
    box-shadow: 0 0 5px rgba(0, 255, 255, 0.5), 0 0 10px rgba(0, 255, 255, 0.3);
  }
  100% {
    box-shadow: 0 0 10px rgba(0, 255, 255, 0.8), 0 0 20px rgba(0, 255, 255, 0.5),
      0 0 30px rgba(255, 0, 255, 0.3);
  }
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.page-title {
  text-align: center;
  font-size: 2.5rem;
  margin-bottom: 2rem;
  color: @primary;
  font-weight: 700;
  letter-spacing: 0.1em;
  text-shadow: 0 0 15px rgba(0, 255, 255, 0.7);
  animation: glow 3s infinite alternate;
}

.dialog-card {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 100;
  width: 90%;
  max-width: 450px;
  background: rgba(10, 10, 26, 0.95);
  backdrop-filter: blur(16px);
  border: 1px solid rgba(0, 255, 255, 0.4);
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 0 20px rgba(0, 255, 255, 0.5);
}

.dialog-title {
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 1.5rem;
  color: @primary;
}

.dialog-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.color-preview {
  height: 42px;
  background-color: #00ffff;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
}

.action-button {
  min-width: 100px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem;
}

.loading-text {
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  color: @primary;
  animation: glow 2s ease-in-out infinite alternate;
}

.loading-indicators {
  display: flex;
  gap: 0.5rem;
}

.loading-bar {
  width: 8px;
  background: rgba(0, 255, 255, 0.3);
  border-radius: 4px;
  animation: load 1.5s ease-in-out infinite;

  &:nth-child(2) {
    animation-delay: 0.2s;
  }

  &:nth-child(3) {
    animation-delay: 0.4s;
  }
}

@keyframes load {
  0%,
  100% {
    height: 15%;
    opacity: 0.3;
  }
  50% {
    height: 100%;
    opacity: 1;
  }
}
.bg-canvas {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}
</style>